<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList">
            <el-button slot="append"
              icon="el-icon-search"
              @click="getUserList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type='primary'
            @click="addDialobVisible = true">添加用户</el-button>
        </el-col>
        <el-col :span="1"
          :push="12">
          <el-tooltip content="刷新"
            placement="top">
            <el-button icon="el-icon-refresh-left"
              class="refresh"
              @click="getUserList"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table :data="userList"
        border
        stripe>
        <el-table-column type="index"
          label="ID">
        </el-table-column>
        <el-table-column label="姓名"
          prop="username">
        </el-table-column>
        <el-table-column label="邮箱"
          prop="email">
        </el-table-column>
        <el-table-column label="电话"
          prop="mobile">
        </el-table-column>
        <el-table-column label="角色"
          prop="role_name">
        </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 slot-scope="scope" 可以拿到当前行的所有数据-->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#DCDFE4"
              @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
          width="170">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary"
              icon="el-icon-edit"
              circle
              size="medium"
              @click="showEditDialog(scope.row.id)">
            </el-button>
            <!-- 删除 -->
            <el-button type="danger"
              icon="el-icon-delete"
              circle
              size="medium"
              @click="removeUserById(scope.row.id)"></el-button>
            <!-- 角色分配 -->
            <el-tooltip content="角色分配"
              placement="top"
              :enterable="false">
              <el-button type="warning"
                icon="el-icon-setting"
                circle
                @click="setRole(scope.row)"
                size="medium"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户"
      :visible.sync="addDialobVisible"
      width="30%"
      @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm"
        :rules="addFromRules"
        ref="addFormRef"
        label-width="70px">
        <el-form-item label="用户名"
          prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码"
          type="password"
          prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱"
          prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机"
          prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
        class="dialog-footer">
        <el-button @click="addDialobVisible = false">
          取 消
        </el-button>
        <el-button type="primary"
          @click="addUser">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户"
      :visible.sync="editDialobVisible"
      width="30%"
      @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"
            :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="邮箱"
          prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机"
          prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
        class="dialog-footer">
        <el-button @click="editDialobVisible = false">
          取 消
        </el-button>
        <el-button type="primary"
          @click="editorUserInfo">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="角色分配"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      @close="setRoleDialogClosed">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配角色：
          <el-select v-model="selectedRoleId"
            placeholder="请选择角色">
            <el-option v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer"
        class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary"
          @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[A-Za-z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号码
    var checkMobile = (rule, value, cb) => {
      // 验证手机号码的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]18|[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialobVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单的验证规则对象
      addFromRules: {
        username: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }, {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            min: 6,
            max: 16,
            message: '密码的长度在6~16个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            // type: 'email',
            validator: checkEmail,
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      // 修改用户对话框的显示
      editDialobVisible: false,
      // 保存查到的用户信息
      editForm: {},
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            // type: 'email',
            validator: checkEmail,
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      // 控制角色分配对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 保存所有的角色列表
      rolesList: [],
      // 已经选中的角色
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页面变化时
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 修改某一行的状态
    async userStateChange (userInfo) {
      // users/:uId/state/:type
      const path = `users/${userInfo.id}/state/${userInfo.mg_state}`
      const { data: res } = await this.$http.put(path)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      // 重置对话框的内容
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        // 发送网络请求添加用户信息
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
        } else {
          this.$message.success('添加用户成功!')
          // 关闭添加用户的对话框
          this.addDialobVisible = false
          // 重新查询用户列表
          this.getUserList()
        }
      })
    },
    // 打开修改用户信息对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
      this.editDialobVisible = true
    },
    // 关闭修改用户信息对框框重置信息框内容
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改的用户信息
    editorUserInfo (id) {
      // 提交验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const param = {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        }
        const { data: res } = await this.$http.put('users/' + this.editForm.id, param)
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败！')
        } else {
          this.$message.success('修改用户信息成功！')
          // 关闭对话框
          this.editDialobVisible = false
          // 重新查询用户列表
          this.getUserList()
        }
      })
    },
    // 根据ID删除用户信息
    async removeUserById (id) {
      // 弹框询问用户是否删除数据
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)

      // 成功：返回的是一个confirm字符串
      // 失败：返回的是一个cancel字符串
      console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除用户
      const { data: rest } = await this.$http.delete('users/' + id)
      if (rest.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功！')
      // 关闭对话框
      this.editDialobVisible = false
      // 重新查询用户列表
      this.getUserList()
    },
    // 展示分配角色的对话框
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前先获取所有的角色列表

      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击确认按钮，分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.setRoleDialogVisible = false
      this.getUserList()
    },
    // 关闭分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
